<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TrainingSession extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'character_id', 'scenario_id', 'session_uuid',
        'status', 'initial_difficulty', 'final_difficulty',
        'final_emotion_score', 'success_achieved', 'session_summary'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'success_achieved' => 'boolean',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    /**
     * 所属用户关系
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * AI角色关系
     */
    public function character()
    {
        return $this->belongsTo(AiCharacter::class, 'character_id');
    }

    /**
     * 训练场景关系
     */
    public function scenario()
    {
        return $this->belongsTo(TrainingScenario::class, 'scenario_id');
    }

    /**
     * 对话消息关系
     */
    public function messages()
    {
        return $this->hasMany(ConversationMessage::class, 'session_id');
    }

    /**
     * 训练复盘关系
     */
    public function review()
    {
        return $this->hasOne(TrainingReview::class, 'session_id');
    }

    /**
     * JSON字段的访问器和修改器
     */
    public function getSessionSummaryAttribute($value)
    {
        return $value ? json_decode($value, true) : null;
    }

    public function setSessionSummaryAttribute($value)
    {
        $this->attributes['session_summary'] = $value ? json_encode($value) : null;
    }

    /**
     * 检查会话是否活跃
     */
    public function isActive()
    {
        return $this->status === 'active';
    }

    /**
     * 检查会话是否已完成
     */
    public function isCompleted()
    {
        return in_array($this->status, ['completed', 'failed']);
    }

    /**
     * 获取会话持续时间（分钟）
     */
    public function getDurationInMinutes()
    {
        if (!$this->completed_at) {
            return null;
        }

        return $this->started_at->diffInMinutes($this->completed_at);
    }
}